'''
Created on Sep 27, 2009

@author: mkiyer
'''

from veggie.app.application import CommandLineApplication
from veggie.app.alignment.bowtie import Bowtie
import logging
import os

class TopHat(CommandLineApplication):
    '''
    TopHat is a fast splice junction mapper for RNA-Seq reads. It aligns 
    RNA-Seq reads to mammalian-sized genomes using the ultra high-throughput 
    short read aligner Bowtie, and then analyzes the mapping results to 
    identify splice junctions between exons. 

    http://tophat.cbcb.umd.edu/index.html
    '''
    _executable = "$SW_ROOT/bioinfo/rnaseq/tophat/current/tophat"

    def run_single_read(self, fastq_file,
                        output_dir=None, 
                        genome="hg18", 
                        options=None, cwd=None):       
        if options:
            self.addOptions(options)
        if cwd:
            self.cwd = cwd            

        index_name = Bowtie.get_index(genome)
        if index_name is None:
            raise KeyError('indexes for genome %s not available' % genome)
            
        # setup environment variable for bowtie indexes
        self.setenv('BOWTIE_INDEXES', Bowtie.get_indexes_path())

        # options for single read tophat
        if output_dir is None:
            output_dir = self.cwd
        
        self.addOptions({'--output-dir': output_dir})
        self.args = [index_name, fastq_file]
        # run the program
        logging.debug(self.getCommandLine())
        return self()

    def run_paired_end(self, mate1_fastq_file, mate2_fastq_file,
                       output_dir=None, 
                       genome="hg18", 
                       options=None, cwd=None):
        if options:
            self.addOptions(options)
        if cwd:
            self.cwd = cwd            

        index_name = Bowtie.get_index(genome)
        if index_name is None:
            raise KeyError('indexes for genome %s not available' % genome)
            
        # setup environment variable for bowtie indexes
        self.setenv('BOWTIE_INDEXES', Bowtie.get_indexes_path())

        if output_dir is None:
            output_dir = self.cwd        
        self.addOptions({'--output-dir': output_dir})        
        self.args = [index_name, mate1_fastq_file, mate2_fastq_file]
        # run the program
        logging.debug(self.getCommandLine())
        return self()